package com.ait.edu.service.impl;

import com.ait.commonutils.exceptionHandler.GuilException;
import com.ait.edu.entity.Chapter;
import com.ait.edu.entity.Video;
import com.ait.edu.entity.chapter.ChapterVo;
import com.ait.edu.entity.chapter.VideoVo;
import com.ait.edu.mapper.ChapterMapper;
import com.ait.edu.service.ChapterService;
import com.ait.edu.service.VideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-06-14
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private VideoService videoService;

    /*
    * 分装数据
    *
    *  data: [{
          id: 1,
          label: '一级 1',
          children: [{
            id: 4,
            label: '二级 1-1',
          },{
          id: 2,
          label: '一级 2',
          children: [{
            id: 4,
            label: '二级 2-1',
          }]
        },
    *
    * 首先要创建两个实体类chapterVo和videoVo来装载数据
    *
    * 返回list
    * */
    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String id) {
        //查询出所有的章节Chapter

        QueryWrapper<Chapter> chapterwrapper = new QueryWrapper<>();
        chapterwrapper.eq("course_id",id);
        List<Chapter> chapterlist = this.list(chapterwrapper);
        //查询出所有的小结Video

        QueryWrapper<Video> videowrapper = new QueryWrapper<>();
        videowrapper.eq("course_id",id);
        List<Video> videoList = videoService.list(videowrapper);

        List<ChapterVo> chapterVos = new ArrayList<>();

        for (Chapter chapter : chapterlist){
            ChapterVo chapterVo = new ChapterVo();
            chapterVo.setId(chapter.getId());
            chapterVo.setTitle(chapter.getTitle());
            List<VideoVo> videoVos = new ArrayList<>();
            chapterVo.setChildren(videoVos);
            chapterVos.add(chapterVo);
            for (Video video : videoList){
                if(video.getChapterId().equals(chapter.getId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video,videoVo);
                    videoVos.add(videoVo);
                }
            }
        }
        return chapterVos;
    }

    //看看章节下有没有小节有的话不能删除
    @Override
    public boolean delChaptervideo(String id) {
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id",id);
        int one = videoService.count(wrapper);
        if(one > 0){
            throw new GuilException(500,"不能进行删除");
        }

        return this.removeById(id);
    }
}
